package db

import (
	"batch_flyway/pkg/model"
	"database/sql"
	"encoding/json"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

type QueryResult struct {
	Row    string         `json:"row"`
	Flyway []model.Flyway `json:"flyway"`
}

func (q *QueryResult) String() string {
	jd, _ := json.Marshal(q)
	return string(jd)
}

func QueryDB(dsn, row, tablename string) (QueryResult, error) {
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		return QueryResult{}, fmt.Errorf("连接数据库失败: %v", err)
	}
	defer db.Close()

	// 查询flyway表
	flyways, err := db.Query(fmt.Sprintf("SELECT installed_rank,version,type,script,installed_by,installed_on,execution_time,success FROM %s where success=0", tablename))
	if err != nil {
		return QueryResult{}, fmt.Errorf("查询Flyway表失败: %v", err)
	}
	defer flyways.Close()

	var FlywayList []model.Flyway
	for flyways.Next() {
		var f model.Flyway
		if err := flyways.Scan(
			&f.InstalledRank,
			&f.Version,
			&f.Type,
			&f.Script,
			&f.InstalledBy,
			&f.InstalledOn,
			&f.ExecutionTime,
			&f.Success,
		); err != nil {
			return QueryResult{}, fmt.Errorf("读取Flyway数据失败: %v", err)
		}
		FlywayList = append(FlywayList, f)

	}
	return QueryResult{
		Row:    row,
		Flyway: FlywayList,
	}, nil
}
